// pages/orderPayment/pay/index.js
const $api = require('../../../../request/api').API;
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    orderList: [],
    beeperType: 0,
    code: '',
    btnForBid: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let scene = decodeURIComponent(options.scene);
    if (scene != 'undefined') {
      this.code = scene.split('hc=')[1];
      app.isLogin(this.getWaitPayOrder);
    }
  },
  // // 判断是否登录
  // async isLogin(){
  //   if(!wx.getStorageSync(Storage.ACCESS_TOKEN)){
  //     await app.login()
  //   }
  //   this.getWaitPayOrder()
  // },
  // 去历史订单
  orderHistory() {
    wx.navigateTo({
      url: '../payHistory/index'
    });
  },

  // 点击支付先获取手机号 - 公用
  // getPhoneNumber (e) {
  //   let cond = {
  //     code :e.detail.code
  //   }
  //   $api.getPhone(cond).then(res=>{
  //     if(res.data.data!=null){
  //       this.setData({
  //         phone:res.data.data
  //       })
  //       // 唤起支付
  //       this.payMoney()
  //     }
  //   })
  // },

  // 支付
  payMoney() {
    let _this = this;
    const orderList = this.data.orderList;
    if (!orderList.some(item => item.selected)) {
      Toast.fail('请至少选择一条订单支付');
      return;
    }
    let params = {
      orderNos: orderList
        .filter(item => item.selected)
        .map(item => item.orderNo)
        .toString(),
      openId: wx.getStorageSync(Storage.USER_OPEN_ID),
      phone: this.data.phone
    };
    $api.scanToPayWaitOrder(params).then(res => {
      console.log('唤起支付回调', res);
      let data = res.data.data;
      // 唤起支付
      wx.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType,
        paySign: data.paySign,
        success(res) {
          Toast.loading({
            message: '支付中...',
            forbidClick: true,
            duration: 10000
          });
          setTimeout(() => {
            _this.getWaitPayOrder(false);
            Toast.success('支付成功');
          }, 10000);
        },
        fail(res) {
          console.log('支付失败回调', res);
        },
        complete(res) {
          console.log('支付complete回调', res);
        }
      });
    });
  },

  // 专属支付
  exclusivePay(e) {
    var _this = this;
    let orderNo = e.currentTarget.dataset.orderno;
    let money = e.currentTarget.dataset.money;
    let params = {
      orderNos: orderNo,
      openId: wx.getStorageSync(Storage.USER_OPEN_ID)
    };
    $api.scanToPayWaitOrder(params).then(res => {
      let data = res.data.data;
      // 唤起支付
      wx.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType,
        paySign: data.paySign,
        success(res) {
          Toast.loading({
            message: '支付中...',
            forbidClick: true,
            duration: 10000
          });
          setTimeout(() => {
            _this.getWaitPayOrder(false);
            Toast.success(`金额:${money},支付成功`);
          }, 10000);
          // setTimeout(() => {
          //   Toast.success(`金额:${money},支付成功`)
          //   _this.getWaitPayOrder()
          // }, 1000);
        },
        fail(res) {
          console.log('支付失败回调', res);
        },
        complete(res) {
          console.log('支付complete回调', res);
        }
      });
    });
  },
  // 选择订单
  selectOrder(e) {
    let orderId = e.currentTarget.dataset.orderid;
    this.data.orderList.find(item => {
      if (item.orderId == orderId) {
        item.selected ? delete item.selected : (item.selected = true);
      }
    });
    this.setData({
      orderList: this.data.orderList
    });
  },
  // 获取当前订单信息
  getWaitPayOrder(pay = true) {
    let _this = this;
    let params = {
      beeperCode: this.code
    };
    $api
      .getWaitPayOrder(params)
      .then(res => {
        if (res.data.data != null) {
          res.data.data.orders.length > 0 ? (res.data.data.orders[0].selected = pay) : '';
          this.setData({
            orderList: res.data.data.orders,
            beeperType: res.data.data.beeperType
          });
        }

        if (this.data.orderList.length == 1 && pay) {
          // 专用订单为1时 直接拉取支付
          let params = {
            orderNos: this.data.orderList[0].orderNo,
            openId: wx.getStorageSync(Storage.USER_OPEN_ID)
          };
          this.setData({
            btnForBid: true
          });
          $api
            .scanToPayWaitOrder(params)
            .then(res => {
              console.log('唤起支付回调-专用', res);
              let data = res.data.data;
              // 唤起支付
              wx.requestPayment({
                timeStamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.signType,
                paySign: data.paySign,
                success(res) {
                  Toast.loading({
                    message: '支付中...',
                    forbidClick: true,
                    duration: 10000
                  });
                  setTimeout(() => {
                    _this.getWaitPayOrder(false);
                    Toast.success(`金额,支付成功`);
                  }, 10000);
                },
                fail(res) {},
                complete(res) {
                  setTimeout(() => {
                    this.setData({
                      btnForBid: false
                    });
                  }, 2000);
                }
              });
            })
            .finally(() => {
              setTimeout(() => {
                this.setData({
                  btnForBid: false
                });
              }, 2000);
            });
        }
      })
      .catch(err => {});
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
